package com.sdtele.tta.dac;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.InvalidPropertiesFormatException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@WebListener
public class AppListener implements ServletContextListener,ServletContextAttributeListener {
	ApplicationContext applicationContext = null;
    public void contextInitialized(ServletContextEvent sce)  {
    }
    public void contextDestroyed(ServletContextEvent sce)  { 
    }
	@Override
	public void attributeAdded(ServletContextAttributeEvent scae) {		
		ServletContext sc = scae.getServletContext();
		if(scae.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)){
			applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
			Dac.getInstance().setJdbcTemplate((JdbcTemplate)applicationContext.getBean("jdbcTemplate")); 
			String sqlXmlFileName = sc.getRealPath("/WEB-INF/sql.xml");
			try {
				Dac.getInstance().getPropSQL().loadFromXML(new FileInputStream(sqlXmlFileName));
			} catch (InvalidPropertiesFormatException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	@Override
	public void attributeRemoved(ServletContextAttributeEvent scae) {		
	}
	@Override
	public void attributeReplaced(ServletContextAttributeEvent scae) {		
	}
}
